package cn.westv.scps.web.controller.sms.tpl;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.xml.soap.Detail;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yunpian.sdk.model.Result;
import com.yunpian.sdk.model.Template;

import cn.westv.scps.constant.ConfigCodeConstant;
import cn.westv.scps.constant.DBconstant;
import cn.westv.scps.domain.SmsTemplateEntity;
import cn.westv.scps.service.sms.template.ISmsTemplateService;
import cn.westv.scps.utils.Page;
import cn.westv.scps.web.controller.base.AbstractController;
import cn.westv.scps.web.controller.sms.tpl.vo.SmsTemplateVO;
import cn.westv.scps.yunpian.TplApi;

@Controller
@RequestMapping("/sms/tpl")
public class TemplateController extends AbstractController<TemplateController> {
	@Resource
	private ISmsTemplateService smsTemplateService;

	/**
	 * 访问分页查询页面
	 * 
	 * @return
	 */
	@RequestMapping("/page/list.cgi")
	public String findPage_cgi() {
		return "/WEB-INF/page/sms/tpl/smsTpl_index.jsp";
	}

	/**
	 * 访问编辑页面
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/edit.cgi")
	public String editPage(String id, HttpServletRequest request) {
		request.setAttribute("id", id);
		return "/WEB-INF/page/sms/tpl/smsTplEdit.jsp";
	}

	/**
	 * 分页查询
	 * 
	 * @param vo
	 * @param page
	 * @return
	 */
	@RequestMapping("/page/list")
	@ResponseBody
	public Map<String, Object> findPage(Date beginTime, Date endTime, SmsTemplateVO vo, Page<SmsTemplateEntity> page) {
		try {
			String hql = "from SmsTemplateEntity where stauts <> ? ";
			ArrayList<Object> params = new ArrayList<>();
			params.add(DBconstant.DELETE_STAUTS);
			if (beginTime != null) {
				hql += " and createTime > ? ";
				params.add(beginTime);
			}
			if (endTime != null) {
				hql += " and createTime < ? ";
				params.add(endTime);
			}
			if (vo != null) {
				SmsTemplateEntity entity = vo.getSmsTemplateEntity();// 从vo中获取对应的实体类
				if (entity != null) {
					// 反射进行hql的拼接
					Field[] fields = entity.getClass().getDeclaredFields();
					for (Field field : fields) {
						field.setAccessible(true);
						Object fieldValueObject = field.get(entity);
						if (fieldValueObject instanceof String) {
							String fielValue = (String) fieldValueObject;
							if (StringUtils.isNotBlank(fielValue)) {
								hql += "and " + field.getName() + " like ?";
								params.add("%" + fielValue + "%");
							}
						}
					}
				}
			}
			Page<SmsTemplateEntity> findPage = smsTemplateService.findPage(hql, page, SmsTemplateEntity.class,
					params.toArray());
			findPage.setLinks(null);
			return ajaxReturnMap(OP_STATUS_SUCCESS, "", findPage);
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 根据id获取详情
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/detail")
	@ResponseBody
	public Map<String, Object> Detail(String id, HttpServletRequest request) {
		try {
			SmsTemplateEntity entity = smsTemplateService.get(SmsTemplateEntity.class, id);
			return ajaxReturnMap(OP_STATUS_SUCCESS, "", entity);
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 更新或者添加
	 * 
	 * @param smsTemplateEntity
	 * @return
	 */
	@RequestMapping("/save")
	@ResponseBody
	public Map<String, Object> save(SmsTemplateEntity smsTemplateEntity) {
		if (smsTemplateEntity == null || StringUtils.isEmpty(smsTemplateEntity.getContent())
				|| StringUtils.isEmpty(smsTemplateEntity.getCode())
				|| StringUtils.isEmpty(smsTemplateEntity.getCompany())) {
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.REQUIRED_PARAMETERS_IS_NULL), null);
		}
		String msg = "";
		try {
			String smsTeplId = smsTemplateEntity.getSmsTeplId();
			if (StringUtils.isNotBlank(smsTeplId)) {
				// 修改
				msg = returnMsg("update_succeed");
				SmsTemplateEntity entityDB = smsTemplateService.get(SmsTemplateEntity.class, smsTeplId);
				if (entityDB != null) {
					if (entityDB.getCode().equals(smsTemplateEntity.getCode())) {
						if (!(entityDB.getContent().trim().equals(smsTemplateEntity.getContent().trim()))
								&& StringUtils.isNotBlank(entityDB.getCheckStatus())) {
							smsTemplateEntity.setCheckStatus("RE_AUDIT");
						}
						copyBeanNotEmptyFields(entityDB, smsTemplateEntity);// 将表单获取到的对象的属性复制持久对象中
						smsTemplateService.saveOrUpdate(entityDB);
					} else {
						return ajaxReturnMap(OP_STATUS_FAILD, "修改失败，code不能修改！", null);
					}
				} else {
					return ajaxReturnMap(OP_STATUS_FAILD, "修改失败，没有这条数据！", null);
				}
			} else {
				// 新增
				msg = returnMsg("add_succeed");
				String code = smsTemplateEntity.getCode();
				List<SmsTemplateEntity> find = smsTemplateService.find("from SmsTemplateEntity where code = ? ",
						SmsTemplateEntity.class, new Object[] { code });// 根据code查询，判断是否存在code重复
				if (find == null || find.size() == 0) {
					smsTemplateEntity.setSmsTeplId(null);
					smsTemplateEntity.setCreateTime(new Date());
					smsTemplateEntity.setStauts(DBconstant.INITIAL_STAUTS);
					smsTemplateEntity.setCheckStatus(DBconstant.INITIAL_STAUTS);
					smsTemplateService.saveOrUpdate(smsTemplateEntity);
				} else {
					return ajaxReturnMap(OP_STATUS_FAILD, "添加失败，code重复！", null);
				}
			}
			return ajaxReturnMap(OP_STATUS_SUCCESS, msg, null);
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 删除
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping("/del")
	@ResponseBody
	public Map<String, Object> del(String ids) {
		try {
			if (StringUtils.isNotBlank(ids)) {
				String[] idArr = ids.split(",");
				for (String id : idArr) {
					SmsTemplateEntity entity = smsTemplateService.get(SmsTemplateEntity.class, id);
					entity.setStauts(DBconstant.DELETE_STAUTS);
					smsTemplateService.saveOrUpdate(entity);
				}
				return ajaxReturnMap(OP_STATUS_SUCCESS, returnMsg(ConfigCodeConstant.DEL_SUCCEED), null);
			} else {
				return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.REQUIRED_PARAMETERS_IS_NULL), null);
			}
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 批量提交模板至审核
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping("/audit")
	@ResponseBody
	public Map<String, Object> audit(String ids) {
		try {
			Result<Template> result = null;
			// List<Result<Template>> list = new ArrayList<>();
			if (StringUtils.isNotBlank(ids)) {
				String[] idArr = ids.split(",");
				for (String id : idArr) {
					SmsTemplateEntity entity = smsTemplateService.get(SmsTemplateEntity.class, id);// 根据id找出对应的模板
					TplApi ta = new TplApi();
					String company = entity.getCompany();
					String content = entity.getContent();
					result = ta.add("【" + company + "】" + content, null);// 想云片提交模板
//					System.out.println(result);
					// list.add(result);
					Integer code = result.getCode();// 返回码
					if (code == 0) {// 返回码为0，则正确提交，但并不是立即就审核通过
						Template data = result.getData();
						Long tplId = data.getTpl_id();
						entity.setTplId(tplId.toString());// 将获取到的云片网关对应的模板ID写入持久类对象
						String checkStatus = data.getCheck_status();
						entity.setCheckStatus(checkStatus);// 将获取到的审核状态写入持久类对象
						smsTemplateService.saveOrUpdate(entity);// 保存至数据库
					} else {

					}
				}
			}
			return ajaxReturnMap(OP_STATUS_SUCCESS, "已经提交至网关进行审核！<br>提交结果：<br>" + result, null);
		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 提交重新审核修改后的模板
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/reaudit")
	@ResponseBody
	public Map<String, Object> reAuditTpl(String id) {
		if (StringUtils.isEmpty(id)) {
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.REQUIRED_PARAMETERS_IS_NULL), null);
		}
		try {
			SmsTemplateEntity entity = smsTemplateService.get(SmsTemplateEntity.class, id);
			if (entity != null) {
				TplApi ta = new TplApi();
				Result<Template> result = null;
				result = ta.update(entity.getTplId(), "【" + entity.getCompany() + "】" + entity.getContent());
				Integer code = result.getCode();
				if (code == 0) {
					entity.setCheckStatus(result.getData().getCheck_status());
					smsTemplateService.saveOrUpdate(entity);
				}
				return ajaxReturnMap(OP_STATUS_FAILD, "已经提交审核！<br>提交结果：<br>" + result, null);
			} else {
				return ajaxReturnMap(OP_STATUS_FAILD, "没有该短信模板！  ", null);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 刷新模板审核状态
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping("/latest/status")
	@ResponseBody
	public Map<String, Object> latestStatus(String ids) {
		try {

			TplApi ta = new TplApi();
			Result<List<Template>> result = null;

			if (StringUtils.isNotBlank(ids)) {
				if (StringUtils.isNotBlank(ids)) {
					String[] idArr = ids.split(",");
					for (String id : idArr) {
						SmsTemplateEntity entity = smsTemplateService.get(SmsTemplateEntity.class, id);// 找到对应模板
						result = ta.get(entity.getTplId());// 向云片网关获取对应模板
						refreshSmsTpl(result);

					}
				}
			} else {
				result = ta.get(null);// 向云片网关获取所有模板
				// System.out.println(result);
			}
//			System.out.println(result);
			Integer code = result.getCode();
			if (code == 0) {// 正确获取到模板
				refreshSmsTpl(result);
				return ajaxReturnMap(OP_STATUS_SUCCESS, "刷新成功！", null);
			} else {
				return ajaxReturnMap(OP_STATUS_FAILD, "刷新失败！", null);
			}

		} catch (Exception e) {
			logErr(e);
			return ajaxReturnMap(OP_STATUS_FAILD, returnMsg(ConfigCodeConstant.UNKNOWN_ERR), null);
		}
	}

	/**
	 * 刷新数据库中模板的状态，如果没有，则新增进去
	 * 
	 * @param result
	 */
	private void refreshSmsTpl(Result<List<Template>> result) {
		try {
			List<Template> list = result.getData();
			if (list.size() > 0) {
				for (Template template : list) {// 便利获取到的模板集合，将所有的状态都更新
					List<SmsTemplateEntity> find = smsTemplateService.find("from SmsTemplateEntity where tplId = ?",
							SmsTemplateEntity.class, new Object[] { template.getTpl_id().toString() });// 对应的查询出数据库的模板
					SmsTemplateEntity smsTemplateEntity = null;
					if (find != null && find.size() > 0) {
						smsTemplateEntity = find.get(0);
						smsTemplateEntity.setCheckStatus(template.getCheck_status());// 更新审核状态
						smsTemplateEntity.setStauts(DBconstant.INITIAL_STAUTS);
					} else {
						smsTemplateEntity = new SmsTemplateEntity();
						smsTemplateEntity.setTplId(template.getTpl_id().toString());
						smsTemplateEntity.setCheckStatus(template.getCheck_status());
						String tpl_content = template.getTpl_content();
						tpl_content = tpl_content.replace("【", "");
						String[] split = tpl_content.split("】");
						smsTemplateEntity.setCompany(split[0]);
						smsTemplateEntity.setContent(split[1]);
						smsTemplateEntity.setCreateTime(new Date());
						smsTemplateEntity.setStauts(DBconstant.INITIAL_STAUTS);
					}
					if (smsTemplateEntity != null)
						smsTemplateService.saveOrUpdate(smsTemplateEntity);
				}
			}
		} catch (Exception e) {
			logErr(e);
		}
	}

}
